package com.atguigu.yygh.orders.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.orders.service.WeiXinService;
import com.atguigu.yygh.orders.util.HttpClient;
import com.atguigu.yygh.orders.util.HttpRequestHelper;

import com.atguigu.yygh.hosp.client.HospitalFeignClient;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.orders.mapper.OrderInfoMapper;
import com.atguigu.yygh.orders.service.OrderInfoService;
import com.atguigu.yygh.rabbit.enums.MqConst;
import com.atguigu.yygh.rabbit.service.RabbitService;
import com.atguigu.yygh.user.client.PatientFeignClient;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderCountQueryVo;
import com.atguigu.yygh.vo.order.OrderCountVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.atguigu.yygh.vo.order.OrderQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.impl.client.HttpClients;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author ztz
 * @since 2022-03-17
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private WeiXinService weiXinService;
    @Autowired
    private HospitalFeignClient hospitalFeignClient;

    @Autowired
    private PatientFeignClient patientFeignClient;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private OrderInfoMapper orderInfoMapper;


    //根据订单单号查询详细数据
    @Override
    public OrderInfo getOrders(Integer orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);

        if (StringUtils.isEmpty(orderInfo)) {
            throw new YyghException(20001, "订单详情查询不到!");
        }
        this.packageOrder(orderInfo);
        return orderInfo;
    }

    @Override
    public OrderInfo getOrders(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);

        if (StringUtils.isEmpty(orderInfo)) {
            throw new YyghException(20001, "订单详情查询不到!");
        }
        this.packageOrder(orderInfo);
        return orderInfo;
    }

    //根据条件查询，分页
    @Override
    public Page<OrderInfo> getPageList(Page iPage, OrderQueryVo orderQueryVo) {
        // 获取查询条件
        //orderQueryVo获取条件值
        String name = orderQueryVo.getKeyword(); //医院名称
        Long patientId = orderQueryVo.getPatientId(); //就诊人名称
        String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();

        Long userId = orderQueryVo.getUserId();

        //对条件值进行非空判断
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(userId)) {
            wrapper.eq("user_id", userId);
        }
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("hosname", name);
        }
        if (!StringUtils.isEmpty(patientId)) {
            wrapper.eq("patient_id", patientId);
        }
        if (!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status", orderStatus);
        }
        if (!StringUtils.isEmpty(reserveDate)) {
            wrapper.ge("reserve_date", reserveDate);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time", createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time", createTimeEnd);
        }

        Page selectPage = baseMapper.selectPage(iPage, wrapper);

        List<OrderInfo> orders = selectPage.getRecords();

        for (OrderInfo order : orders) {
            this.packageOrder(order);
        }
        return selectPage;
    }

    //封装数据
    private void packageOrder(OrderInfo order) {
        Integer status = order.getOrderStatus();
        order.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(status));
    }

    //创建订单
    @Override
    public Long saveOrder(String scheduleId, Long patientId) {

        // 首先我们获取排班数据
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);
        // 获取就诊人数据
        Patient patient = patientFeignClient.getPatientOrder(patientId);
        // 远程调用医院自身接口进行远程数据确认
        //3 平台里面 ==> 调用医院订单确认接口，
        // 3.1 如果医院返回失败，挂号失败
        //使用map集合封装需要传过医院数据
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode", scheduleOrderVo.getHoscode());
        paramMap.put("depcode", scheduleOrderVo.getDepcode());
        paramMap.put("hosScheduleId", scheduleOrderVo.getHosScheduleId());
        paramMap.put("reserveDate", new DateTime(scheduleOrderVo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", scheduleOrderVo.getReserveTime());
        paramMap.put("amount", scheduleOrderVo.getAmount()); //挂号费用
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType", patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex", patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone", patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode", patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode", patient.getDistrictCode());
        paramMap.put("address", patient.getAddress());
        //联系人
        paramMap.put("contactsName", patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo", patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone", patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        //String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", "");

        //使用httpclient发送请求，请求医院接口
        JSONObject result =
                HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/submitOrder");
        //根据医院接口返回状态码判断  200 成功
        if (result.getInteger("code") == 200) {
            // 返回结果成功
            // 我们进行数据封装
            OrderInfo orderInfo = new OrderInfo();
            BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
            //医师id
            orderInfo.setScheduleId(scheduleId);
            //就诊人id
            orderInfo.setPatientId(patientId);
            // 就诊人信息封装
            orderInfo.setUserId(patient.getUserId());
            orderInfo.setPatientName(patient.getName());
            orderInfo.setPatientPhone(patient.getPhone());

            // 获取返回的数据
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约号序
            Integer number = jsonObject.getInteger("number");
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");

            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            //订单状态
            orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
            // 订单交易号
            String outTradeNo = System.currentTimeMillis() + "" + new Random().nextInt(100);
            orderInfo.setOutTradeNo(outTradeNo);

            // 4保存订单
            int insert = baseMapper.insert(orderInfo);

            System.out.println(insert);


            //TODO 5 根据医院返回数据，更新排班数量
            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");

            // 进行数据传输
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setAvailableNumber(availableNumber);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setScheduleId(scheduleId);

            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(patient.getPhone());
            orderMqVo.setMsmVo(msmVo);

            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
            return orderInfo.getId();

        } else { //挂号失败
            throw new YyghException(20001, "挂号失败");
        }
    }

    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
        List<OrderCountVo> orderCountVo = orderInfoMapper.getCountByOrderCountVo(orderCountQueryVo);

        List<String> collect = orderCountVo.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        List<Integer> collect1 = orderCountVo.stream().map(OrderCountVo::getCount).collect(Collectors.toList());

        HashMap<String, Object> map = new HashMap<>();
        map.put("dateList", collect);
        map.put("countList", collect1);
        return map;
    }

    //每日八点进行医师提醒
    @Override
    public void patientTips(String dateString) {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.ge("reserve_date", dateString);
        wrapper.ne("order_status", OrderStatusEnum.CANCLE.getStatus());

        List<OrderInfo> orderInfos = baseMapper.selectList(wrapper);

        for (OrderInfo orderInfo : orderInfos) {
            // 给用户发送短信
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());

            // 给接受rabbit消息得服务端发送消息
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }

    }

    /**
     * 取消订单
     *
     * @param orderId
     */
    @Override
    public Boolean cancelOrder(Long orderId) {

        // 首先我们需要发送信息给医院端口 是否可以取消预约
        OrderInfo orders = this.getOrders(orderId);

        DateTime time = new DateTime(orders.getQuitTime());
        if (time.isBeforeNow()) {
            throw new YyghException(20001, "当前时间已经超过可以取消预约的时间");
        }

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode", orders.getHoscode());
        paramMap.put("hosRecordId", orders.getHosRecordId());

        JSONObject jsonObject = HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/updateCancelStatus");

        // 然后判断是否成功
        if (StringUtils.isEmpty(jsonObject) && jsonObject.getInteger("code") != 200) {
            throw new YyghException(ResultCodeEnum.FAIL.getCode(), jsonObject.getString("message"));
        } else {
            if (orders.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus()) {
                // 可以取消预约，调用取消方法
                Boolean aBoolean = weiXinService.refund(orderId);

                if (!aBoolean) {
                    // 给hosp端发送消息进行数据更新发送消息
                    throw new YyghException(20001, "退款失败");
                }
            }

            //更改订单状态
            orders.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
            this.updateById(orders);

            // 统一进行数据更新
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(orders.getScheduleId());

            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orders.getPatientPhone());
            orderMqVo.setMsmVo(msmVo);

            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
            return true;
        }
    }
}
